package com.yiren.manager.ctrl.base;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrStaffPayRecord;
import com.yiren.entity.YrUserRfidCard;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.ctrl.elder.YrElderBaseController;
import com.yiren.manager.form.base.YrUserRfidCardForm;
import com.yiren.manager.form.beds.YrHouseTypeForm;
import com.yiren.manager.service.iface.base.YrUserRfidCardService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("userRfidCard")
@Controller
public class YrUserRfidCardController extends YrElderBaseController<YrUserRfidCardForm, YrUserRfidCard> {

	@Autowired
	private YrUserRfidCardService selfService;

	@Autowired
	private YrMealCardService mealCardService;
	
	@Autowired
	private YrElderWalletService elderWallerService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	// 保存实体
	@RequestMapping("/saveHandle")
	@ResponseBody
	public HTTPResult<YrUserRfidCardForm> saveHandle(String data)
			throws SwallowException, MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrUserRfidCardForm> result = new HTTPResult<YrUserRfidCardForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrUserRfidCardForm form = tool.mapper("userRfidCard", YrUserRfidCardForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		String sqlWhere = "card_number=?1 AND status=0";
		QueryResult<YrUserRfidCard> qrUserRfidCard = selfService.find(YrUserRfidCard.class, sqlWhere,new Object[]{form.getCardNumber()});
		if(!qrUserRfidCard.getResultList().isEmpty()){
			throwExp("当前卡号已经存在，请勿重复办理");
		}
		YrMealCard mealCard = null;
		form.setUserRfidCardId(UUIDGenerator.getUUID());
		form.setCreateTime(new Date());
		form.setStatus(0);// 设置为正常使用状态
		sqlWhere = "card_card_id=?1";
		QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere,
				new Object[] { form.getUserCardId() });
		if (qrMealCard.getTotalRecord() == 0) {// 没有饭卡记录
			// 新增一张饭卡
			mealCard = new YrMealCard();
			mealCard.setMealCardId(UUIDGenerator.getUUID());
			mealCard.setCardPersonId(form.getUserRelationId());
			mealCard.setCardPersonName(form.getPersonName());
			mealCard.setCardCardId(form.getUserCardId());
			mealCard.setBalance(Float.valueOf(0));//设置余额
			mealCard.setPreBalance(Float.valueOf(0));//设置赠送余额
			mealCard.setCardType(0);
			mealCard.setCreateTime(new Date());
			mealCard.setCreateId(form.getCreateId());
			mealCard.setPersonType(form.getUserType());
		}
		
		
		YrElderPayRecord elderPayRecord = null;
		
		YrStaffPayRecord staffPayRecord = null;
		
		YrElderWallet elderWallet = null;
		
		if(form.getUserType()==1){//长者
			YrElder elder = elderService.findOne(form.getUserRelationId());
			if(null==elder){
				throwExp("查询不到老者相关信息");
			}
			sqlWhere = "elder_id=?1 AND be_status<>2";
			
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class, sqlWhere, new Object[]{form.getUserRelationId()});
			if(qrElderBeHospital.getResultList().isEmpty()){
				throwExp("查询不到相关老者住院登记信息");
			}
			YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
			
			if(form.getPayWay()==2){//如果是钱包支付
				sqlWhere = "elder_id=?1";
				QueryResult<YrElderWallet> qrElderWallet = elderWallerService.find(YrElderWallet.class,sqlWhere, new Object[]{form.getUserRelationId()});
				if(qrElderWallet.getTotalRecord()==0){
					throwExp("该老者暂无钱包");
				}
				elderWallet = qrElderWallet.getResultList().get(0);
				if(elderWallet.getWalletBalance()-form.getPrice()<0){
					throwExp("该老者钱包余额不足");
				}
				elderWallet.setWalletBalance(elderWallet.getWalletBalance()-form.getPrice());//扣掉钱包的钱
			}
			elderPayRecord = costElderPayRecord(elderBeHospital.getBeHospitalId(),"rfid卡费用", elder, 11, form.getUserRfidCardId(), form.getPrice(),
					form.getPayWay(),0,form.getCreateId(),1);
			elderPayRecord.setSubjectRoomId("-1");//设置为资产部门
		}else{//员工
			YrStaffInfo staffInfo = staffInfoService.findOne(form.getUserRelationId());
			if(null==staffInfo){
				throwExp("查询不到该员工相关信息");
			}
			staffPayRecord = new YrStaffPayRecord();
			staffPayRecord.setElderPayRecordId(UUIDGenerator.getUUID());
			staffPayRecord.setCostDesc("rfid卡费用");
			staffPayRecord.setPayDate(new Date());
			staffPayRecord.setStaffId(staffInfo.getStaffId());
			staffPayRecord.setStaffCardId(staffInfo.getCardId());
			staffPayRecord.setStaffName(staffInfo.getName());
			staffPayRecord.setPayStatus(1);
			staffPayRecord.setPayWay(1);//支付方式为现金
			staffPayRecord.setCostType(1);
			staffPayRecord.setCreateTime(new Date());
			staffPayRecord.setRelationId(form.getUserRfidCardId());
			staffPayRecord.setPayMoney(form.getPrice());
		}
		
		
		YrUserRfidCard entity = ObjectUtils.objectToObject(form, YrUserRfidCard.class);
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrUserRfidCard.class, entity);
		favorites.putFavorite(YrMealCard.class, mealCard);
		favorites.putFavorite(YrElderWallet.class, elderWallet);
		favorites.putFavorite(YrStaffPayRecord.class, staffPayRecord);
		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);

		selfService.addByFavorites(favorites);

		return result;
	}

	@RequestMapping("writeOff")
	@ResponseBody
	public HTTPResult<YrUserRfidCardForm> writeOff(String id) throws MyException {
		HTTPResult<YrUserRfidCardForm> result = new HTTPResult<YrUserRfidCardForm>();
		if (StringUtil.isEmpty(id)) {
			throwExp("参数有误");
		}
		YrUserRfidCard entity = selfService.findOne(id);
		if (null == entity) {
			throwExp("该rfid卡不存在");
		}
		entity.setStatus(1);// 设置为注销状态
		selfService.save(entity);
		return result;
	}

	/**
	 * 批量删除
	 * 
	 * @param data
	 * @return
	 * @throws SwallowException
	 * @throws MyException
	 */
	@RequestMapping("writeOffBatch")
	@ResponseBody
	public HTTPResult<YrHouseTypeForm> writeOffBatch(String data) throws SwallowException, MyException {
		HTTPResult<YrHouseTypeForm> result = new HTTPResult<YrHouseTypeForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		String[] ids = tool.mapper("ids", String[].class);
		if (null == ids) {
			throwExp("param.error");
		}
		for (String id : ids) {
			YrUserRfidCard entity = selfService.findOne(id);
			if (null != entity) {
				entity.setStatus(1);// 设置为注销状态
				selfService.save(entity);
			}
		}
		return result;
	}

	/**
	 * 根据证件号码或姓名查找
	 * 
	 * @param searchVal
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrUserRfidCardForm> find(String searchVal) throws Exception {
		HTTPResult<YrUserRfidCardForm> result = new HTTPResult<YrUserRfidCardForm>();
		String sqlWhere = "(person_name=?1 OR user_card_id=?2) AND status=0";
		QueryResult<YrUserRfidCard> qrUserRfidCard = selfService.find(YrUserRfidCard.class, sqlWhere,
				new Object[] { searchVal, searchVal });
		List<YrUserRfidCardForm> formList = new ArrayList<YrUserRfidCardForm>();
		for (YrUserRfidCard entity : qrUserRfidCard.getResultList()) {
			formList.add(toForm(entity));
		}
		result.setData(formList);
		return result;
	}

	@Override
	public YrUserRfidCardForm toForm(YrUserRfidCard e) throws Exception {
		YrUserRfidCardForm form = ObjectUtils.objectToObject(e, YrUserRfidCardForm.class);
		return form;
	}

	@Override
	public YrUserRfidCard toEntity(YrUserRfidCardForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
